<?php
/**
 * @author Minh Luan
 * @copyright 2013 HCMC University of Science
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
 
require_once($CFG->libdir . '/adminlib.php');
require_once($CFG->libdir . '/accesslib.php'); //dùng hàm has_capability
require_once($CFG->dirroot . '/lib/moodlelib.php');	//Sử dụng hàm getdate để lấy dữ liệu ngày tháng
require_once('phpmailer/class.phpmailer.php');
/*Navigation Init*/
/**
 * itusurveyplugin_extends_navigation()
 * 
 * @param mixed $navigation
 * @return
 */
function itusurveyplugin_extends_navigation(global_navigation $navigation) {
        $nodeITUSurvey 		= $navigation->add('ITU Survey');
        /******************************************************************************************
	    *						QUESTION MANAGEMENT
    	******************************************************************************************/
        //To manage question: survey creator only
        if(has_capability('local/itusurveyplugin:managequestion', context_system::instance())) {
            $nodeQuestionManagement = 
            $nodeITUSurvey->add('ITU Question Management', new moodle_url($CFG->wwwroot.'/local/itusurveyplugin/ituquestion/ituquestionmanagement.php'));
	    }
        /******************************************************************************************
	    *						ITU SURVEY MANAGEMENT
    	******************************************************************************************/
        //To manage survey: add edit delete extend-survey creator only 
        if(has_capability('local/itusurveyplugin:manageitusurvey', context_system::instance())) {
            $nodeITUSurveyManagement = 
            $nodeITUSurvey->add('ITU Survey Management', new moodle_url($CFG->wwwroot.'/local/itusurveyplugin/itusurvey/surveymanagement.php'));
	    }
        // To view current status of survey: survey creator and survey manager
        if(has_capability('local/itusurveyplugin:viewitusurvey', context_system::instance())) {
            $nodeITUSurveyStatistic = $nodeITUSurvey->add('ITU Survey Statistic', new moodle_url($CFG->wwwroot.'/local/itusurveyplugin/itusurveyreport/surveystatistic.php'));
	    }
        /******************************************************************************************
	    *						ITU SURVEY CLONE
    	******************************************************************************************/
        //To manage survey: add edit delete extend-survey creator only 
        if(has_capability('local/itusurveyplugin:manageitusurvey', context_system::instance())) {
            $nodeITUSurveyClone = 
            $nodeITUSurvey->add('ITU Survey Clone', new moodle_url($CFG->wwwroot.'/local/itusurveyplugin/itusurvey/clone_survey.php'));
	    }
        /******************************************************************************************
	    *						ITU SURVEY BENCHMARK
    	******************************************************************************************/
        // To view benchmark of expired surveys: survey creator and survey manager
        if(has_capability('local/itusurveyplugin:viewbenchmark', context_system::instance())) {
            $nodeITUSurveyBenchMark = 
            $nodeITUSurvey->add('ITU Survey Benchmark', new moodle_url($CFG->wwwroot.'/local/itusurveyplugin/itusurveyreport/benchmark.php'));
	    }
        /******************************************************************************************
	    *						ITU SURVEY NOTIFICATION
    	******************************************************************************************/
        // To view benchmark of expired surveys: survey creator and survey manager
        if(has_capability('local/itusurveyplugin:doitusurvey', context_system::instance())) {
            $nodeITUSurveyFilling = 
            $nodeITUSurvey->add('ITU Survey Notification', new moodle_url($CFG->wwwroot.'/local/itusurveyplugin/itusurveyfilling/notification.php'));
	    }
        
        $nodeITUSurvey->forceopen = true;
}



/*DEFINE CONSTANT FOR MESSAGES BEGIN*/

/*DEFINE CONSTANT FOR MESSAGES END*/
class question_management
{
     /**
      * question_management::add_itu_question()
      * 
      * @param mixed $question
      * @return
      */
     public function add_itu_question($question) 
     {
     global $DB;
     $temp = NULL;
     $temp = $DB->insert_record('itu_questions',$question,$returnid=true);
      return $temp;
     }
     /**
      * question_management::add_ddl_answer()
      * 
      * @param mixed $record
      * @return
      */
     public function add_ddl_answer($record)
     {
        global $DB;
        if($DB->insert_record('ans_ddl_def',$record))
        return true;
        else
        return false;
     }
     /**
      * question_management::add_cbx_answer()
      * 
      * @param mixed $record
      * @return
      */
     public function add_cbx_answer($record)
     {
         global $DB;
        if($DB->insert_record('ans_cbx_def',$record))
        return true;
        else
        return false;
        
     }
     /**
      * question_management::add_scale_answer()
      * 
      * @param mixed $record
      * @return
      */
     public function add_scale_answer($record)
     {
         global $DB;
        if($DB->insert_record('ans_scale_def',$record))
        return true;
        else
        return false;
        
     }
     /**
      * question_management::update_itu_question()
      * 
      * @param mixed $question
      * @return
      */
     public function update_itu_question($question)
     {
        global $DB;
        if($DB->update_record('itu_questions',$question))
        return true;
        else
        return false;
     }
     /**
      * question_management::update_ddl_answer()
      * 
      * @param mixed $record
      * @return
      */
     public function update_ddl_answer($record)
     {
        global $DB;
        if($DB->update_record('ans_ddl_def',$record))
        return true;
        else
        return false;
     }
     /**
      * question_management::update_cbx_answer()
      * 
      * @param mixed $record
      * @return
      */
     public function update_cbx_answer($record)
     {
        global $DB;
        if($DB->update_record('ans_cbx_def',$record))
        return true;
        else
        return false;
     }
          /**
           * question_management::update_scale_answer()
           * 
           * @param mixed $record
           * @return
           */
          public function update_scale_answer($record)
     {
        global $DB;
        if($DB->update_record('ans_scale_def',$record))
        return true;
        else
        return false;
     }
     
     
}


/*DEFINE CLASS AND FUNCTION BEGIN*/
class survey_management
{
    /**
     * survey_management::search_itu_survey()
     * 
     * @param mixed $keyword
     * @param mixed $program_id
     * @param mixed $major_id
     * @return
     */
    public function search_itu_survey($keyword, $program_id, $major_id) 
    {
        global $DB;
        $sql = 'select * from survey';
        $surveys = $DB->get_records_sql($sql);
    	return $surveys;
    }
    
    /**
     * survey_management::get_all_survey()
     * 
     * @return
     */
    public function get_all_survey()
    {
        global $DB;
        $sql = 'select * from survey';
        $surveys = $DB->get_records_sql($sql);
    	return $surveys;
    }
    
    /**
     * survey_management::add_survey()
     * 
     * @param mixed $survey_data
     * @param mixed $majors
     * @param mixed $questions
     * @return
     */
    public function add_survey($survey_data, $majors, $questions)
    {
        global $DB;
        $survey_id = $DB->insert_record('itu_survey', $survey_data, $returnid=true, $bulk=false);
        
        //Cloned Programs
        $program_id = $survey_data["itus_program"];
        $program = $DB->get_record('program', array('id'=>$program_id));
        $program_clone = array(
                        "sp_program"=>$program->id,
                        "sp_code"=>$program->program_id,
                        "sp_name"=>$program->program_name,
                        "sp_level"=>$program->program_level,
                        "sp_type"=>$program->program_type,
                        "sp_description"=>$program->program_description,
                        "sp_survey"=>$survey_id
                        );
        $DB->insert_record('surveyed_programs', $program_clone, $returnid=false, $bulk=false);
        
        //Cloned Majors
        $major = array();
        $major_clone = array();
        foreach($majors as $major){
            $major = $DB->get_record('major', array('id'=>$major));
            $major_clone = array(
                        "sm_major"=>$major->id,
                        "sm_code"=>$major->major_id,
                        "sm_name"=>$major->major_name,
                        "sm_description"=>$major->description,
                        "sm_program"=>$major->program_id,
                        "sm_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_majors', $major_clone, $returnid=false, $bulk=false);
        }
        
        //Cloned Subjects
        $subject = array();
        $subject_clone = array();
        $subjects = $DB->get_records('subject', array('program_id'=>$program_id));
        foreach($subjects as $subject){
            $subject_clone = array(
                        "ss_subject"=>$subject->id,
                        "ss_code"=>$subject->subject_id,
                        "ss_name_en"=>$subject->subject_name_en,
                        "ss_name_vn"=>$subject->subject_name_vn,
                        "ss_credit"=>$subject->subject_credit,
                        "ss_theory_hr"=>$subject->subject_theory_hr,
                        "ss_practice_hr"=>$subject->subject_practice_hr,
                        "ss_abstract"=>$subject->abstract,
                        "ss_goal"=>"",
                        "ss_program"=>$program_id,
                        "ss_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_subjects', $subject_clone, $returnid=false, $bulk=false);
        }
        
        //Cloned Teachers
        $teachers = array();
        $teacher_clone = array();
        $uniqueCombination = array();
        //reuse above subjects array
        foreach($subjects as $subject){
            $teachers = $DB->get_records('teacher_subject', array('subject'=>$subject->id));
            foreach($teachers as $teacher){
                $userInfor = $DB->get_record('user', array('id'=>$teacher->teacher));
                $teacher_clone = array(
                        "st_teacher"=>$userInfor->id,
                        "st_fullname"=>$userInfor->lastname." ".$userInfor->firstname,
                        "st_email"=>$userInfor->email,
                        "st_survey"=>$survey_id,
                        "st_subject"=>$teacher->subject
                );
                $DB->insert_record('surveyed_teachers', $teacher_clone, $returnid=false, $bulk=false);
                
                //Create unique composite key for Survey-Teacher-Subject-and Status
                $uniqueCombination = array(
                        "sts_subject_id"=>$subject->id,
                        "sts_teacher_id"=>$teacher->teacher,
                        "sts_survey_id"=>$survey_id,
                        "sts_status"=>0
                );
                $DB->insert_record('itus_teachers_subjects', $uniqueCombination, $returnid=false, $bulk=false);
            }
        }
        
        //Add Questions
        $counter = 1;
        $question_itus = array();
		if(count($questions) > 0){
			foreach($questions as $question){
				$question_itus = array(
							"qi_order"=>$counter,
							"qi_itus"=>$survey_id,
							"qi_question"=>$question
				);
				$DB->insert_record('question_itus', $question_itus, $returnid=false, $bulk=false);
				$counter++;
			}
		}
        
        
        //Clone Learning Outcomes
        $los = $DB->get_records('learning_outcome', array('program_id'=>$program_id));
        $loInfo = array();
        foreach($los as $lo){
            $loInfo = array(
                    "sl_lo"=>$lo->id,
                    "sl_code"=>$lo->lo_id,
                    "sl_level"=>$lo->lo_level,
                    "sl_name"=>$lo->lo_name,
                    "sl_parent_lo"=>$lo->parent_lo_id,
                    "sl_program"=>$lo->program_id,
                    "sl_survey"=>$survey_id
            );
            
            $DB->insert_record('surveyed_los', $loInfo, $returnid=false, $bulk=false);
        }
        
    }
    
    /**
     * survey_management::draft_survey()
     * 
     * @param mixed $survey_data
     * @param mixed $majors
     * @param mixed $questions
     * @return
     */
    public function draft_survey($survey_data, $majors, $questions){
        global $DB;
        unset($survey_data["itus_publish_date"]);
        $survey_id = $DB->insert_record('itu_survey', $survey_data, $returnid=true, $bulk=false);
        
        //Cloned Programs
        $program_id = $survey_data["itus_program"];
        $program = $DB->get_record('program', array('id'=>$program_id));
        $program_clone = array(
                        "sp_program"=>$program->id,
                        "sp_code"=>$program->program_id,
                        "sp_name"=>$program->program_name,
                        "sp_level"=>$program->program_level,
                        "sp_type"=>$program->program_type,
                        "sp_description"=>$program->program_description,
                        "sp_survey"=>$survey_id
                        );
        $DB->insert_record('surveyed_programs', $program_clone, $returnid=true, $bulk=false);
        
        //Cloned Majors
        $major = array();
        $major_clone = array();
        foreach($majors as $major){
            $major = $DB->get_record('major', array('id'=>$major));
            $major_clone = array(
                        "sm_major"=>$major->id,
                        "sm_code"=>$major->major_id,
                        "sm_name"=>$major->major_name,
                        "sm_description"=>$major->description,
                        "sm_program"=>$major->program_id,
                        "sm_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_majors', $major_clone, $returnid=true, $bulk=false);
        }
        
        //Cloned Subjects
        $subject = array();
        $subject_clone = array();
        $subjects = $DB->get_records('subject', array('program_id'=>$program_id));
        foreach($subjects as $subject){
            $subject_clone = array(
                        "ss_subject"=>$subject->id,
                        "ss_code"=>$subject->subject_id,
                        "ss_name_en"=>$subject->subject_name_en,
                        "ss_name_vn"=>$subject->subject_name_vn,
                        "ss_credit"=>$subject->subject_credit,
                        "ss_theory_hr"=>$subject->subject_theory_hr,
                        "ss_practice_hr"=>$subject->subject_practice_hr,
                        "ss_abstract"=>$subject->abstract,
                        "ss_goal"=>"",
                        "ss_program"=>$program_id,
                        "ss_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_subjects', $subject_clone, $returnid=false, $bulk=false);
        }
        
        //Cloned Teachers
        $teachers = array();
        $teacher_clone = array();
        $uniqueCombination = array();
        //reuse above subjects array
        foreach($subjects as $subject){
            $teachers = $DB->get_records('teacher_subject', array('subject'=>$subject->id));
            foreach($teachers as $teacher){
                $userInfor = $DB->get_record('user', array('id'=>$teacher->teacher));
                $teacher_clone = array(
                        "st_teacher"=>$userInfor->id,
                        "st_fullname"=>$userInfor->lastname." ".$userInfor->firstname,
                        "st_email"=>$userInfor->email,
                        "st_survey"=>$survey_id,
                        "st_subject"=>$teacher->subject
                );
                $DB->insert_record('surveyed_teachers', $teacher_clone, $returnid=false, $bulk=false);
                
                //Create unique composite key for Survey-Teacher-Subject-and Status
                $uniqueCombination = array(
                        "sts_subject_id"=>$subject->id,
                        "sts_teacher_id"=>$teacher->teacher,
                        "sts_survey_id"=>$survey_id,
                        "sts_status"=>0
                );
                $DB->insert_record('itus_teachers_subjects', $uniqueCombination, $returnid=false, $bulk=false);
            }
        }
        
        //Add Questions
        $counter = 1;
        $question_itus = array();
		if(count($questions) > 0){
			foreach($questions as $question){
				$question_itus = array(
							"qi_order"=>$counter,
							"qi_itus"=>$survey_id,
							"qi_question"=>$question
				);
				$DB->insert_record('question_itus', $question_itus, $returnid=false, $bulk=false);
				$counter++;
			}

		}
        
        //Clone Learning Outcomes
        $los = $DB->get_records('learning_outcome', array('program_id'=>$program_id));
        $loInfo = array();
        foreach($los as $lo){
            $loInfo = array(
                    "sl_lo"=>$lo->id,
                    "sl_code"=>$lo->lo_id,
                    "sl_level"=>$lo->lo_level,
                    "sl_name"=>$lo->lo_name,
                    "sl_parent_lo"=>$lo->parent_lo_id,
                    "sl_program"=>$lo->program_id,
                    "sl_survey"=>$survey_id
            );
            $DB->insert_record('surveyed_los', $loInfo, $returnid=false, $bulk=false);
        }
    }
    
    
    /**
     * survey_management::clearSurveyData()
     * 
     * @param mixed $survey_id
     * @return
     */
    public function clearSurveyData($survey_id){
        global $DB;
        //delete cloned program
        $DB->delete_records("surveyed_programs", array("sp_survey"=>$survey_id));
        //delete cloned major
        $DB->delete_records("surveyed_majors", array("sm_survey"=>$survey_id));
        //delete cloned subject
        $DB->delete_records("surveyed_subjects", array("ss_survey"=>$survey_id));
        //delete cloned teacher
        $DB->delete_records("surveyed_teachers", array("st_survey"=>$survey_id));
        //delete cloned lo
        $DB->delete_records("surveyed_los", array("sl_survey"=>$survey_id));
        //delete teach subject survey
        $DB->delete_records("itus_teachers_subjects", array("sts_survey_id"=>$survey_id));        
        //delete question-itus
        $DB->delete_records("question_itus", array("qi_itus"=>$survey_id)); 
    }
    
    /**
     * survey_management::edit_survey_and_draft()
     * 
     * @param mixed $survey_data
     * @param mixed $majors
     * @param mixed $questions
     * @return
     */
    public function edit_survey_and_draft ($survey_data, $majors, $questions){
        global $DB;
        //Update Survey Information
        unset($survey_data["itus_publish_date"]);
        $survey_id = $survey_data["id"]; 
        $DB->update_record('itu_survey', $survey_data, $bulk=false);
        //Reclone everything
        //Cloned Programs
        $program_id = $survey_data["itus_program"];
        $program = $DB->get_record('program', array('id'=>$program_id));
        $program_clone = array(
                        "sp_program"=>$program->id,
                        "sp_code"=>$program->program_id,
                        "sp_name"=>$program->program_name,
                        "sp_level"=>$program->program_level,
                        "sp_type"=>$program->program_type,
                        "sp_description"=>$program->program_description,
                        "sp_survey"=>$survey_id
                        );
        $DB->insert_record('surveyed_programs', $program_clone, $returnid=true, $bulk=false);
        
        //Cloned Majors
        $major = array();
        $major_clone = array();
        foreach($majors as $major){
            $major = $DB->get_record('major', array('id'=>$major));
            $major_clone = array(
                        "sm_major"=>$major->id,
                        "sm_code"=>$major->major_id,
                        "sm_name"=>$major->major_name,
                        "sm_description"=>$major->description,
                        "sm_program"=>$major->program_id,
                        "sm_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_majors', $major_clone, $returnid=true, $bulk=false);
        }
        
        //Cloned Subjects
        $subject = array();
        $subject_clone = array();
        $subjects = $DB->get_records('subject', array('program_id'=>$program_id));
        foreach($subjects as $subject){
            $subject_clone = array(
                        "ss_subject"=>$subject->id,
                        "ss_code"=>$subject->subject_id,
                        "ss_name_en"=>$subject->subject_name_en,
                        "ss_name_vn"=>$subject->subject_name_vn,
                        "ss_credit"=>$subject->subject_credit,
                        "ss_theory_hr"=>$subject->subject_theory_hr,
                        "ss_practice_hr"=>$subject->subject_practice_hr,
                        "ss_abstract"=>$subject->abstract,
                        "ss_goal"=>"",
                        "ss_program"=>$program_id,
                        "ss_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_subjects', $subject_clone, $returnid=false, $bulk=false);
        }
        
        //Cloned Teachers
        $teachers = array();
        $teacher_clone = array();
        $uniqueCombination = array();
        //reuse above subjects array
        foreach($subjects as $subject){
            $teachers = $DB->get_records('teacher_subject', array('subject'=>$subject->id));
            foreach($teachers as $teacher){
                $userInfor = $DB->get_record('user', array('id'=>$teacher->teacher));
                $teacher_clone = array(
                        "st_teacher"=>$userInfor->id,
                        "st_fullname"=>$userInfor->lastname." ".$userInfor->firstname,
                        "st_email"=>$userInfor->email,
                        "st_survey"=>$survey_id,
                        "st_subject"=>$teacher->subject
                );
                $DB->insert_record('surveyed_teachers', $teacher_clone, $returnid=false, $bulk=false);
                
                //Create unique composite key for Survey-Teacher-Subject-and Status
                $uniqueCombination = array(
                        "sts_subject_id"=>$subject->id,
                        "sts_teacher_id"=>$teacher->teacher,
                        "sts_survey_id"=>$survey_id,
                        "sts_status"=>0
                );
                $DB->insert_record('itus_teachers_subjects', $uniqueCombination, $returnid=false, $bulk=false);
            }
        }
        
        //Add Questions
        $counter = 1;
        $question_itus = array();
        if(count($questions) > 0){
            foreach($questions as $question){
                $question_itus = array(
                            "qi_order"=>$counter,
                            "qi_itus"=>$survey_id,
                            "qi_question"=>$question
                );
                $DB->insert_record('question_itus', $question_itus, $returnid=false, $bulk=false);
                $counter++;
            }
        }
            
        
        //Clone Learning Outcomes
        $los = $DB->get_records('learning_outcome', array('program_id'=>$program_id));
        $loInfo = array();
        foreach($los as $lo){
            $loInfo = array(
                    "sl_lo"=>$lo->id,
                    "sl_code"=>$lo->lo_id,
                    "sl_level"=>$lo->lo_level,
                    "sl_name"=>$lo->lo_name,
                    "sl_parent_lo"=>$lo->parent_lo_id,
                    "sl_program"=>$lo->program_id,
                    "sl_survey"=>$survey_id
            );
            $DB->insert_record('surveyed_los', $loInfo, $returnid=false, $bulk=false);
        }
    }
    
    /**
     * survey_management::edit_survey_and_publish()
     * 
     * @param mixed $survey_data
     * @param mixed $majors
     * @param mixed $questions
     * @return
     */
    public function edit_survey_and_publish ($survey_data, $majors, $questions){
        global $DB;
        //Update Survey Information
        $survey_id = $survey_data["id"];
        $DB->update_record('itu_survey', $survey_data, $bulk=false);
        //Reclone everything
        //Cloned Programs
        $program_id = $survey_data["itus_program"];
        $program = $DB->get_record('program', array('id'=>$program_id));
        $program_clone = array(
                        "sp_program"=>$program->id,
                        "sp_code"=>$program->program_id,
                        "sp_name"=>$program->program_name,
                        "sp_level"=>$program->program_level,
                        "sp_type"=>$program->program_type,
                        "sp_description"=>$program->program_description,
                        "sp_survey"=>$survey_id
                        );
        $DB->insert_record('surveyed_programs', $program_clone, $returnid=true, $bulk=false);
        
        //Cloned Majors
        $major = array();
        $major_clone = array();
        foreach($majors as $major){
            $major = $DB->get_record('major', array('id'=>$major));
            $major_clone = array(
                        "sm_major"=>$major->id,
                        "sm_code"=>$major->major_id,
                        "sm_name"=>$major->major_name,
                        "sm_description"=>$major->description,
                        "sm_program"=>$major->program_id,
                        "sm_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_majors', $major_clone, $returnid=true, $bulk=false);
        }
        
        //Cloned Subjects
        $subject = array();
        $subject_clone = array();
        $subjects = $DB->get_records('subject', array('program_id'=>$program_id));
        foreach($subjects as $subject){
            $subject_clone = array(
                        "ss_subject"=>$subject->id,
                        "ss_code"=>$subject->subject_id,
                        "ss_name_en"=>$subject->subject_name_en,
                        "ss_name_vn"=>$subject->subject_name_vn,
                        "ss_credit"=>$subject->subject_credit,
                        "ss_theory_hr"=>$subject->subject_theory_hr,
                        "ss_practice_hr"=>$subject->subject_practice_hr,
                        "ss_abstract"=>$subject->abstract,
                        "ss_goal"=>"",
                        "ss_program"=>$program_id,
                        "ss_survey"=>$survey_id
                        );
            $DB->insert_record('surveyed_subjects', $subject_clone, $returnid=false, $bulk=false);
        }
        
        //Cloned Teachers
        $teachers = array();
        $teacher_clone = array();
        $uniqueCombination = array();
        //reuse above subjects array
        foreach($subjects as $subject){
            $teachers = $DB->get_records('teacher_subject', array('subject'=>$subject->id));
            foreach($teachers as $teacher){
                $userInfor = $DB->get_record('user', array('id'=>$teacher->teacher));
                $teacher_clone = array(
                        "st_teacher"=>$userInfor->id,
                        "st_fullname"=>$userInfor->lastname." ".$userInfor->firstname,
                        "st_email"=>$userInfor->email,
                        "st_survey"=>$survey_id,
                        "st_subject"=>$teacher->subject
                );
                $DB->insert_record('surveyed_teachers', $teacher_clone, $returnid=false, $bulk=false);
                
                //Create unique composite key for Survey-Teacher-Subject-and Status
                $uniqueCombination = array(
                        "sts_subject_id"=>$subject->id,
                        "sts_teacher_id"=>$teacher->teacher,
                        "sts_survey_id"=>$survey_id,
                        "sts_status"=>0
                );
                $DB->insert_record('itus_teachers_subjects', $uniqueCombination, $returnid=false, $bulk=false);
            }
        }
        
        //Add Questions
        $counter = 1;
        $question_itus = array();
        foreach($questions as $question){
                $question_itus = array(
                            "qi_order"=>$counter,
                            "qi_itus"=>$survey_id,
                            "qi_question"=>$question
                );
                $DB->insert_record('question_itus', $question_itus, $returnid=false, $bulk=false);
                $counter++;
        }
        
        //Clone Learning Outcomes
        $los = $DB->get_records('learning_outcome', array('program_id'=>$program_id));
        $loInfo = array();
        foreach($los as $lo){
            $loInfo = array(
                    "sl_lo"=>$lo->id,
                    "sl_code"=>$lo->lo_id,
                    "sl_level"=>$lo->lo_level,
                    "sl_name"=>$lo->lo_name,
                    "sl_parent_lo"=>$lo->parent_lo_id,
                    "sl_program"=>$lo->program_id,
                    "sl_survey"=>$survey_id
            );
            $DB->insert_record('surveyed_los', $loInfo, $returnid=false, $bulk=false);
        }
    }
    
    /**
     * survey_management::clone_survey()
     * 
     * @param mixed $survey
     * @param mixed $user
     * @return
     */
    public function clone_survey ($survey, $user){
        global $DB;
        //CLONE SURVEY ITSELF
        $nowInt = time();
        $now = getdate($nowInt);
        
        
        
        $expiredDate = intval($surveyInfor["itus_expire_date"]);
        if($expiredDate <= $nowInt){
            $expireDate = $nowInt + ONE_WEEK;
            $expiration = getdate($expireDate);    
        }else{
            $expiration = getdate($expiredDate);
        }
    
        $surveyInfor = $DB->get_record('itu_survey', array('id'=>$survey));
        $newSurveyData = array(
                "itus_program"=>$surveyInfor->itus_program,
                "itus_creator"=>$user,
                "itus_create_date"=>$now["year"].'-'.$now["mon"].'-'.$now["mday"].' '.$now["hours"].':'.$now["minutes"].':'.$now["seconds"],
                "itus_update_date"=>$now["year"].'-'.$now["mon"].'-'.$now["mday"].' '.$now["hours"].':'.$now["minutes"].':'.$now["seconds"],
                "itus_title"=>$surveyInfor->itus_title,
                "itus_expire_date"=>$expiration["year"].'-'.$expiration["mon"].'-'.$expiration["mday"].' '.$expiration["hours"].':'.$expiration["minutes"].':'.$expiration["seconds"],
                "itus_publish_date"=>null,
                "itus_depth_lo"=>$surveyInfor->itus_depth_lo,
                "itus_summary_title"=>$surveyInfor->itus_summary_title,
                "itus_summary"=>$surveyInfor->itus_summary,
                "itus_question_title"=>$surveyInfor->itus_question_title,
                "itus_question_summary"=>$surveyInfor->itus_question_summary,
                "itus_lo_title"=>$surveyInfor->itus_lo_title,
                "itus_lo_summary"=>$surveyInfor->itus_lo_summary
        );
        $newID = $DB->insert_record('itu_survey', $newSurveyData, $returnid=true, $bulk=false);
        
        //CLONE RELATED DATA
        //CLONE PROGRAM
        $program = $DB->get_record('surveyed_programs', array('sp_survey'=>$survey));
        $new_program_data = array(
                        "sp_program"=>$program->sp_program,
                        "sp_code"=>$program->sp_code,
                        "sp_name"=>$program->sp_name,
                        "sp_level"=>$program->sp_level,
                        "sp_type"=>$program->sp_type,
                        "sp_description"=>$program->sp_description,
                        "sp_survey"=>$newID
                        );
        $DB->insert_record('surveyed_programs', $new_program_data, $returnid=false, $bulk=false);
        
        //CLONE MAJOR
        $majors = $DB->get_records('surveyed_majors', array('sm_survey'=>$survey));
        $new_major_data = array();
        foreach($majors as $major){
            $new_major_data = array(
                        "sm_major"=>$major->sm_major,
                        "sm_code"=>$major->sm_code,
                        "sm_name"=>$major->sm_name,
                        "sm_description"=>$major->sm_description,
                        "sm_program"=>$major->sm_program,                        
                        "sm_survey"=>$newID
            );
            $DB->insert_record('surveyed_majors', $new_major_data, $returnid=false, $bulk=false);
        }
        
        //CLONE SUBJECT & //CLONE TEACHER
        $new_subject_data = array();
        $new_teacher_data = array();
        $uniqueCombination = array();
        $subjects = $DB->get_records('surveyed_subjects', array('ss_survey'=>$survey));
        foreach($subjects as $subject){
            $new_subject_data = array(
                        "ss_subject"=>$subject->ss_subject,
                        "ss_code"=>$subject->ss_code,
                        "ss_name_en"=>$subject->ss_name_en,
                        "ss_name_vn"=>$subject->ss_name_vn,
                        "ss_credit"=>$subject->ss_credit,
                        "ss_theory_hr"=>$subject->ss_theory_hr,
                        "ss_practice_hr"=>$subject->ss_practice_hr,
                        "ss_abstract"=>$subject->ss_abstract,
                        "ss_goal"=>$subject->ss_goal,
                        "ss_program"=>$subject->ss_program,
                        "ss_survey"=>$newID
                        );
            $DB->insert_record('surveyed_subjects', $new_subject_data, $returnid=false, $bulk=false);
            
            
            //TEACHER of SUBJECT
            $teachers = $DB->get_records('surveyed_teachers', array('st_survey'=>$survey,"st_subject"=>$subject->ss_subject));
            foreach($teachers as $teacher){
                $new_teacher_data = array(
                            "st_teacher"=>$teacher->st_teacher,
                            "st_fullname"=>$teacher->st_fullname,
                            "st_email"=>$teacher->st_email,
                            "st_survey"=>$newID,
                            "st_subject"=>$teacher->st_subject
                    );
                $DB->insert_record('surveyed_teachers', $new_teacher_data, $returnid=false, $bulk=false);
                
                    //Create unique composite key for Survey-Teacher-Subject-and Status
                    $uniqueCombination = array(
                            "sts_subject_id"=>$subject->ss_subject,
                            "sts_teacher_id"=>$teacher->st_teacher,
                            "sts_survey_id"=>$newID,
                            "sts_status"=>0
                    );
                    $DB->insert_record('itus_teachers_subjects', $uniqueCombination, $returnid=false, $bulk=false);
            }
        }
        
        //CLONE QUESTION
        $question_itus = array();
        $questions = $DB->get_records('question_itus', array('qi_itus'=>$survey));
        if(count($questions) > 0){
            foreach($questions as $question){
                $question_itus = array(
                            "qi_order"=>$question->qi_order,
                            "qi_itus"=>$newID,
                            "qi_question"=>$question->qi_question
                );
                $DB->insert_record('question_itus', $question_itus, $returnid=false, $bulk=false);
            }
        }
        
        //CLONE LO
        $los = $DB->get_records('surveyed_los', array('sl_survey'=>$survey));
        $loInfo = array();
        foreach($los as $lo){
            $loInfo = array(
                    "sl_lo"=>$lo->sl_lo,
                    "sl_code"=>$lo->sl_code,
                    "sl_level"=>$lo->sl_level,
                    "sl_name"=>$lo->sl_name,
                    "sl_parent_lo"=>$lo->sl_parent_lo,
                    "sl_program"=>$lo->sl_program,
                    "sl_survey"=>$newID
            );
            $DB->insert_record('surveyed_los', $loInfo, $returnid=false, $bulk=false);
        }
        return $newID;            
    }
    
    /**
     * survey_management::extend_survey()
     * 
     * @param mixed $survey
     * @param mixed $days
     * @return
     */
    public function extend_survey ($survey, $days){
        global $DB;
        //get cur expire date
        $expireDate = $DB->get_record_sql("select itus_expire_date from mdl_itu_survey where id = ?", array($survey));
        //get value from object
        $valueExpireDate = $expireDate->itus_expire_date;
        //add days
        $newExpireDate = strftime("%Y-%m-%d %H:%M:%S", strtotime("$valueExpireDate +".$days." day"));
        //update database
        $DB->update_record("itu_survey", array("id"=>$survey, "itus_expire_date"=>$newExpireDate), $bulk=true);
    }
    
    /**
     * survey_management::delete_survey()
     * 
     * @param mixed $survey
     * @return
     */
    public function delete_survey ($survey){
        global $DB;
        //Delete Surveyed Program, Majors, Subjects, Teachers, value of Comment, ITU, Answers, Questions, LOs, itu survey
        //Delete surveyed program
         $DB->delete_records("surveyed_programs", array("sp_survey"=>$survey));
         $DB->delete_records("surveyed_majors", array("sm_survey"=>$survey));
         $DB->delete_records("surveyed_subjects", array("ss_survey"=>$survey));
         $DB->delete_records("surveyed_teachers", array("st_survey"=>$survey));
         
         $stss = $DB->get_records("itus_teachers_subjects", array("sts_survey_id"=>$survey));
         foreach($stss as $sts){
            $DB->delete_records("slo_comment", array("slo_sts"=>$sts->id));
            $DB->delete_records("slo_value", array("slov_sts"=>$sts->id));
            
            $DB->delete_records("ans_ddl", array("ad_sts"=>$sts->id));
            $DB->delete_records("ans_plain", array("ap_sts"=>$sts->id));
            $DB->delete_records("ans_cbx", array("ac_sts"=>$sts->id)); 
            $DB->delete_records("ans_scale", array("as_sts"=>$sts->id));
            
            $DB->delete_records("itus_teachers_subjects", array("id"=>$sts->id));
         }
         
         $DB->delete_records("surveyed_los", array("sl_survey"=>$survey));
         $DB->delete_records("question_itus", array("qi_itus"=>$survey));
         $DB->delete_records("itu_survey", array("id"=>$survey));
    }
    
    //Support function
    //Recursive function to display LOs in reviewSurvey.php page
    /**
     * survey_management::displayChildLoDownToLevInReview()
     * 
     * @param mixed $code
     * @return
     */
     public function displayChildLoDownToLevInReview($survey_id, $lev, $deepest, $parentLo, $dblib, &$outputStr, $sts_id){
        //echo "surveyid:".$survey_id."/";
        //echo "curlevel:".$lev."/";
        //echo "deepest:".$deepest."/";
        //echo "parentLo:".$parentLo."/";
        $childLos = $dblib->getLoOfLevelOfSurvey($survey_id, $lev, $parentLo);
        //echo "count childLos:".count($childLos)."/";
        foreach($childLos as $childLo){
            //$outputStr .= "<tr>";
            $numbOfSpaces = $lev * 2;
                    if(($lev) == $deepest){
                        //echo "<td>".$childLo->lo_id."</td>";
                        //$outputStr .= "<td>&nbsp;</td>";
                        $outputStr .= "<div name=\"".$childLo->id."\" id=\"".$childLo->id."\" style=\"background-color:#b0c4de; width:58%; float:left; border-bottom:1px coral solid \">";
                        for($i = 1; $i <= $numbOfSpaces; $i++){
                            $outputStr .= "&nbsp;";    
                        }
                        $outputStr .= "<a id=\"".$childLo->id."\"></a>";
                        $outputStr .= $childLo->sl_name;  
                        $outputStr .= "</div>";
                        //$outputStr .= "<td>";
                        $outputStr .= "<div style=\"width:21%; float:left;\">";
                        $outputStr .="<table>";
                        $outputStr .="<tr>";
                        $outputStr .="<td>";
                        //get values:
                        for($i = 1; $i <=3; $i++){
                            $itu = $this->getITUValue($sts_id,$childLo->sl_lo,$i); 
                            if($itu > 0){
                                if($i == 1)
                                    $outputStr .= "<input name='ituCheckbox_".$childLo->id."' id='ituCheckbox_".$childLo->id."' type='checkbox' checked='checked' disabled='disabled'/>I <br/>";
                                if($i == 2) 
                                    $outputStr .= "<input name='ituCheckbox_".$childLo->id."' id='ituCheckbox_".$childLo->id."' type='checkbox' checked='checked' disabled='disabled'/>T <br/>";
                                if($i == 3)
                                    $outputStr .= "<input name='ituCheckbox_".$childLo->id."' id='ituCheckbox_".$childLo->id."' type='checkbox' checked='checked' disabled='disabled'/>U <br/>";
                            }else{
                                if($i == 1)
                                    $outputStr .= "<input name='ituCheckbox_".$childLo->id."' id='ituCheckbox_".$childLo->id."' type='checkbox' disabled='disabled'/>I <br/>";
                                if($i == 2)
                                    $outputStr .= "<input name='ituCheckbox_".$childLo->id."' id='ituCheckbox_".$childLo->id."' type='checkbox' disabled='disabled'/>T <br/>";
                                if($i == 3)
                                    $outputStr .= "<input name='ituCheckbox_".$childLo->id."' id='ituCheckbox_".$childLo->id."' type='checkbox' disabled='disabled'/>U <br/>";
                            }
                        }
                                

                        $outputStr .="</td>";
                        $outputStr .="</tr>";
                        $outputStr .="</table>";
                        $outputStr .= "</div>";
                        //$outputStr .= "</td>";
                        //$outputStr .= "<td>&nbsp;</td>";
                       
                        $outputStr .= "<div style=\"width:20%; float:left;\">";
                        
                        $outputStr .= "<div id=\"assessmentLO_block_".$childLo->sl_lo."\" style=\"border-left: 1px coral solid;\">";
                        //display assess and teach method
                        $assessStr = $this->getAssessTeachMethod($sts_id, $childLo->sl_lo);
                        $outputStr .= $assessStr;                        
                        $outputStr .= "</div>";
                        $outputStr .= "</div>";
                    }else if(($lev) < $deepest && ($dblib->hasLoChild($childLo->sl_code) <= 0)){
                        $outputStr .= "<div style=\"width:60%; float:left; cursor:pointer;\">";
                        for($i = 1; $i <= $numbOfSpaces; $i++){
                            $outputStr .= "&nbsp;";    
                        }
                        $outputStr .= $childLo->sl_code . "---";
                        $outputStr .= $childLo->sl_name;
                        $outputStr .= "</div>";
                        $outputStr .= "<div style=\"width:10%; float:left;\">&nbsp;</div><div style=\"width:30%; float:left;\"></div>";
                        //$outputStr .= "<td colspan='2'>&nbsp;</td>"; 
                    }else if(($lev) < $deepest && ($dblib->hasLoChild($childLo->sl_code) > 0)){
                        $outputStr .= "<div style=\"width:60%; float:left; cursor:pointer;\" onclick=\"$('#child_lo_block_".$childLo->id."').toggle();\">";
                        for($i = 1; $i <= $numbOfSpaces; $i++){
                            $outputStr .= "&nbsp;";    
                        }
                        $outputStr .= $childLo->sl_code . "---";
                        $outputStr .= $childLo->sl_name;
                        $outputStr .= "</div>";
                        $outputStr .= "<div style=\"width:10%; float:left;\">&nbsp;</div><div style=\"width:30%; float:left;\"></div>";
                        //$outputStr .= "<br/>";
                        //$outputStr .= "<td colspan='2'>&nbsp;</td>";
                        //if(($lev) < $deepest && ($dblib->hasLoChild($childLo->lo_id) > 0)){
                        $outputStr .= "<div id=\"child_lo_block_".$childLo->id."\">"; 
                            $this->displayChildLoDownToLevInReview($survey_id, $lev+1, $deepest, $childLo->sl_code, $dblib, &$outputStr, $sts_id);
                        $outputStr .= "</div>";     
                        //}
                        //echo "<td colspan='2'>&nbsp;sdafds</td>"; 
                    }
            //$outputStr .= "</tr>";
                
        }           
        return $outputStr;
    }
    
    //Support function
    //Recursive function to display LOs in do_survey.php page
    /**
     * survey_management::displayChildLoDownToLev()
     * 
     * @param mixed $code
     * @return
     */
    public function displayChildLoDownToLev($survey_id, $lev, $deepest, $parentLo, $dblib, &$outputStr, $sts_id){
        //echo "surveyid:".$survey_id."/";
        //echo "curlevel:".$lev."/";
        //echo "deepest:".$deepest."/";
        //echo "parentLo:".$parentLo."/";
        $childLos = $dblib->getLoOfLevelOfSurvey($survey_id, $lev, $parentLo);
        //echo "count childLos:".count($childLos)."/";
        foreach($childLos as $childLo){
            //$outputStr .= "<tr>";
            $numbOfSpaces = $lev * 2;
                    if(($lev) == $deepest){
                        //echo "<td>".$childLo->lo_id."</td>";
                        //$outputStr .= "<td>&nbsp;</td>";
                        $outputStr .= "<div style=\"background-color:#b0c4de; width:58%; float:left; border-bottom:1px coral solid \">";
                        for($i = 1; $i <= $numbOfSpaces; $i++){
                            $outputStr .= "&nbsp;";    
                        }
                        $outputStr .= $childLo->sl_name;  
                        $outputStr .= "</div>";
                        //$outputStr .= "<td>";
                        $outputStr .= "<div style=\"width:21%; float:left;\">";
                        $outputStr .="<table>";
                        $outputStr .="<tr>";
                        $outputStr .="<td>";
                        //get values:
                        for($i = 1; $i <=3; $i++){
                            $itu = $this->getITUValue($sts_id,$childLo->sl_lo,$i); 
                            if($itu > 0){
                                if($i == 1)
                                    $outputStr .= "<input name='ituCheckbox_'".$childLo->sl_lo." id='ituCheckbox_'".$childLo->sl_lo." type='checkbox' checked='checked' onclick=\"save_itu_value(".$sts_id.",".$childLo->sl_lo.",this.checked, 1)\"/> I ";
                                if($i == 2) 
                                    $outputStr .= "<input name='ituCheckbox_'".$childLo->sl_lo." id='ituCheckbox_'".$childLo->sl_lo." type='checkbox' checked='checked' onclick=\"save_itu_value(".$sts_id.",".$childLo->sl_lo.",this.checked, 2)\"/> T ";
                                if($i == 3)
                                    $outputStr .= "<input name='ituCheckbox_'".$childLo->sl_lo." id='ituCheckbox_'".$childLo->sl_lo." type='checkbox' checked='checked' onclick=\"save_itu_value(".$sts_id.",".$childLo->sl_lo.",this.checked, 3)\"/> U ";
                            }else{
                                if($i == 1)
                                    $outputStr .= "<input name='ituCheckbox_'".$childLo->sl_lo." id='ituCheckbox_'".$childLo->sl_lo." type='checkbox' onclick=\"save_itu_value(".$sts_id.",".$childLo->sl_lo.",this.checked, 1)\"/> I ";
                                if($i == 2)
                                    $outputStr .= "<input name='ituCheckbox_'".$childLo->sl_lo." id='ituCheckbox_'".$childLo->sl_lo." type='checkbox' onclick=\"save_itu_value(".$sts_id.",".$childLo->sl_lo.",this.checked, 2)\"/> T ";
                                if($i == 3)
                                    $outputStr .= "<input name='ituCheckbox_'".$childLo->sl_lo." id='ituCheckbox_'".$childLo->sl_lo." type='checkbox' onclick=\"save_itu_value(".$sts_id.",".$childLo->sl_lo.",this.checked, 3)\"/> U ";
                            }
                        }
                        $outputStr .="</td>";
                        $outputStr .="</tr>";
                        $outputStr .="</table>";
                        $outputStr .= "</div>";
                        //$outputStr .= "</td>";
                        //$outputStr .= "<td>&nbsp;</td>";
                       
                        $outputStr .= "<div style=\"width:20%; float:left;\">";
                       
                        $outputStr .= "<div id=\"assessmentLO_block_".$childLo->sl_lo."\" style=\"border-left: 1px coral solid;\">";
                        //display assess and teach method
                        $assessStr = $this->getAssessTeachMethod($sts_id, $childLo->sl_lo);
                        $outputStr .= $assessStr;                        
                        $outputStr .= "</div>";
                        $outputStr .= "<img src=\"../css/images/edit.jpg\" alt=\"INPUT\"/ style=\"cursor:pointer;\" ";
                        //set position of modal form, set title, set content (in case of editing)
                        $outputStr .=  "onclick=\"$('#dialog_form' ).dialog({ position:{ my:'left top',at:'left bottom',of:this}}); $('#dialog_form').dialog({title:'".$childLo->sl_name."'});";
                        $outputStr .= "$('#input_assessment').val($('#assessmentLO_block_".$childLo->sl_lo."').html()); $('#assessmentLO_block_".$childLo->sl_lo."').css({'color':'black'});";
                        $outputStr .=  " $('#lo_id').val('".$childLo->sl_lo."'); $('#dialog_form').dialog('open');\">";
                        $outputStr .= "</div>";
                    }else if(($lev) < $deepest && ($dblib->hasLoChild($childLo->sl_code) <= 0)){
                        $outputStr .= "<div style=\"width:60%; float:left; cursor:pointer;\">";
                        for($i = 1; $i <= $numbOfSpaces; $i++){
                            $outputStr .= "&nbsp;";    
                        }
                        $outputStr .= $childLo->sl_code . "---";
                        $outputStr .= $childLo->sl_name;
                        $outputStr .= "</div>";
                        $outputStr .= "<div style=\"width:10%; float:left;\">&nbsp;</div><div style=\"width:30%; float:left;\"></div>";
                        //$outputStr .= "<td colspan='2'>&nbsp;</td>"; 
                    }else if(($lev) < $deepest && ($dblib->hasLoChild($childLo->sl_code) > 0)){
                        $outputStr .= "<div style=\"width:60%; float:left; cursor:pointer;\" onclick=\"$('#child_lo_block_".$childLo->id."').toggle();\">";
                        for($i = 1; $i <= $numbOfSpaces; $i++){
                            $outputStr .= "&nbsp;";    
                        }
                        $outputStr .= $childLo->sl_code . "---";
                        $outputStr .= $childLo->sl_name;
                        $outputStr .= "</div>";
                        $outputStr .= "<div style=\"width:10%; float:left;\">&nbsp;</div><div style=\"width:30%; float:left;\"></div>";
                        //$outputStr .= "<br/>";
                        //$outputStr .= "<td colspan='2'>&nbsp;</td>";
                        //if(($lev) < $deepest && ($dblib->hasLoChild($childLo->lo_id) > 0)){
                        $outputStr .= "<div id=\"child_lo_block_".$childLo->id."\">"; 
                            $this->displayChildLoDownToLev($survey_id, $lev+1, $deepest, $childLo->sl_code, $dblib, &$outputStr, $sts_id);
                        $outputStr .= "</div>";     
                        //}
                        //echo "<td colspan='2'>&nbsp;sdafds</td>"; 
                    }
            //$outputStr .= "</tr>";
                
        }           
        return $outputStr;
    }
    
    //Is Survey Expired
    //now() must be greater than 60 mins (instructor can do survey in at least 1 hour) 
    /**
     * survey_management::isSurveyExpired()
     * 
     * @param mixed $survey_id
     * @return
     */
    public function isSurveyExpired($survey_id){
        global $DB;
        $sql = "select count(*) as numb from mdl_itu_survey where id = ? and itus_expire_date > now()";
        $qty = $DB->get_record_sql($sql, array("id"=>$survey_id));
        return $qty->numb <= 0;
    }
    
    //check if los has child or not
    /**
     * survey_management::hasLoChild()
     * 
     * @param mixed $code
     * @return
     */
    public function hasLoChild($code){
        global $DB;
        //echo "select count(id) as childs from mdl_surveyed_los where sl_parent_lo = '$code'";
        $childs = $DB->get_records_sql("select count(id) as childs from mdl_surveyed_los where sl_parent_lo = '$code'",array());
        $number = 0;
        foreach($childs as $record){
            $number = $record->childs;
        }
        return $number;
    }
    
    //get all los at level or los at level and is child of another lo of Specific Program - used in preview_survey
    /**
     * survey_management::getLoOfLevel()
     * 
     * @param mixed $level
     * @param mixed $parent
     * @return
     */
    public function getLoOfLevel($program, $level, $parent){
        global $DB;
        //echo $level."---".$parent."<br/>";
        $los = array();
        $sql1 = "select * from mdl_learning_outcome where lo_level = \"$level\" and parent_lo_id = \"$parent\" and program_id = $program";
        $sql2 = "select * from mdl_learning_outcome where lo_level = \"?\" and program_id = $program";
        if(!is_null($parent)){
            //echo $sql1;
            $los = $DB->get_records_sql($sql1,array());    
        }else{
            //echo $sql2;
            $los = $DB->get_records_sql($sql2,array($level));
        }
        return $los;
    }
    
    //get all los at level or los at level and is child of another lo - of specfic Survey - used in do_survey
    /**
     * survey_management::getLoOfLevelOfSurvey()
     * 
     * @param mixed $survey
     * @param mixed $level
     * @param mixed $parent
     * @return
     */
    public function getLoOfLevelOfSurvey($survey, $level, $parent){
        global $DB;
        $los = array();
        if(!is_null($parent)){
            //echo $sql1."<br/>";
            $los = $DB->get_records_sql("select * from mdl_surveyed_los where sl_level = \"$level\" and sl_parent_lo = \"$parent\" and sl_survey = $survey",array());    
        }else{
            //echo $sql2."<br/>";
            $los = $DB->get_records_sql("select * from mdl_surveyed_los where sl_level = \"$level\" and sl_survey = $survey",array());
        }
        return $los;
    }
    
    //check if assessment exist or not
    /**
     * survey_management::isAssessExist()
     * 
     * @param mixed $sts_id
     * @param mixed $lo_id
     * @return true false
     */
     public function isAssessExist($sts_id, $lo_id){
        global $DB;
        $sql = "select id from mdl_slo_comment where slo_sts = ? and slo_lo = ?";
        $result = $DB->get_record_sql($sql,array($sts_id,$lo_id));
        return $result->id;
     }
     
     //Get asessment and teaching method of LO of subject in survey filled by teacher
     /**
     * survey_management::getAssessTeachMethod()
     * 
     * @param mixed $sts_id
     * @param mixed $lo_id
     * @return string content
     */
     public function getAssessTeachMethod($sts_id, $lo_id){
        global $DB;
        $sql = "select slo_comment from mdl_slo_comment where slo_sts = ? and slo_lo = ?";
        $result = $DB->get_record_sql($sql,array($sts_id,$lo_id));
        return $result->slo_comment;
     }
     
     //Save assessment or teaching method
    /**
     * survey_management::saveAssessTeachMethod()
     * 
     * @param mixed $sts_id
     * @param mixed $lo_id
     * @param mixed $content
     * @return 
     */
     public function saveAssessTeachMethod($sts_id, $lo_id, $content){
        global $DB;
        $assessment = array(
                            "slo_sts"=>$sts_id,
                            "slo_lo"=>$lo_id,
                            "slo_comment"=>$content
        );
        $DB->insert_record('slo_comment', $assessment, $returnid=false, $bulk=false);
     } 
     
    //Update assessment or teaching method
    /**
     * survey_management::updateAssessTeachMethod()
     * 
     * @param mixed $id (pk)
     * @param mixed $content
     * @return 
     */
     public function updateAssessTeachMethod($id, $content){
        global $DB;
        $DB->update_record("slo_comment", array("id"=>$id, "slo_comment"=>$content), $bulk=true);        
     }
     
     //Get ITU value
     /**
     * survey_management::getITUValue()
     * 
     * @param mixed $sts_id
     * @param mixed $lo_id
     * @param mixed $itu (1,2,3-I,T,U)
     * @return $id
     */
     public function getITUValue($sts_id, $lo_id, $ITU){
        global $DB;
        $sql = "select id from mdl_slo_value where slov_sts = ? and slov_lo = ? and slov_value = ?";
        $result = $DB->get_record_sql($sql,array($sts_id,$lo_id,$ITU));
        return $result->id;
     }
     
     //Save ITU Value
    /**
     * survey_management::saveAssessTeachMethod()
     * 
     * @param mixed $sts_id
     * @param mixed $lo_id
     * @param mixed $content
     * @param mixed $typeValue
     * @return 
     */
     public function saveITUValue($sts_id, $lo_id, $typeValue){
        global $DB;
        $ITUvalue = array(
                            "slov_sts"=>$sts_id,
                            "slov_lo"=>$lo_id,
                            "slov_value"=>$typeValue
        );
        $DB->insert_record('slo_value', $ITUvalue, $returnid=false, $bulk=false);
     }
     
     //Delete ITU Value
    /**
     * survey_management::saveAssessTeachMethod()
     * 
     * @param mixed $sts_id
     * @param mixed $lo_id
     * @param mixed $content
     * @param mixed $typeValue
     * @return 
     */
     public function deleteITUValue($idRecord){
        global $DB;
        $DB->delete_records("slo_value", array("id"=>$idRecord));
     }
     
     //Save Answer of Question
    /**
     * survey_management::save_answer()
     * 
     * @param mixed $sts_id
     * @param mixed $question_id
     * @param mixed $input
     * @param mixed $typeOfQuestion
     * @return 
     */
     public function save_answer($sts_id, $question_id, $input, $typeOfQuestion){
        global $DB;
        $ansId = $this->isAnswerExist($sts_id,$question_id,$typeOfQuestion);
        //Plain Text
        if($typeOfQuestion == 1){
            if(strlen($ansId)>0){
                $DB->update_record('ans_plain', array("id"=>$ansId, "ap_sts"=>$sts_id, "ap_question"=>$question_id, "ap_value"=>$input), $bulk=true);                    
            }else{
                $ansVal = array(
                    "ap_sts"=>$sts_id,
                    "ap_question"=>$question_id,
                    "ap_value"=>$input
                );
                $DB->insert_record('ans_plain', $ansVal, $returnid=false, $bulk=false);
            }   
        }else if($typeOfQuestion == 2){
            if(strlen($ansId)>0){    
                $DB->update_record('ans_ddl', array("id"=>$ansId, "ad_sts"=>$sts_id, "ad_question"=>$question_id, "ad_value"=>$input), $bulk=true);                    
            }else{
                $ansVal = array(
                    "ad_sts"=>$sts_id,
                    "ad_question"=>$question_id,
                    "ad_value"=>$input
                );
                $DB->insert_record('ans_ddl', $ansVal, $returnid=false, $bulk=false);
            }   
        }else if($typeOfQuestion == 4){
            if(strlen($ansId)>0){    
                $DB->update_record('ans_scale', array("id"=>$ansId, "as_sts"=>$sts_id, "as_question"=>$question_id, "as_value"=>$input), $bulk=true);                    
            }else{
                $ansVal = array(
                    "as_sts"=>$sts_id,
                    "as_question"=>$question_id,
                    "as_value"=>$input
                );
                $DB->insert_record('ans_scale', $ansVal, $returnid=false, $bulk=false);
            }   
        }
     }
     
     //Save Answer of Question type = checkbox
     /**
     * survey_management::save_answer_of_checkbox()
     * 
     * @param mixed $sts_id
     * @param mixed $question_id
     * @param mixed $input
     * @param mixed $typeOfQuestion
     * @param mixed $state
     * @return 
     */
     public function save_answer_of_checkbox($sts_id, $question_id, $input, $state){
        global $DB;
        //$ansId = $this->isAnswerExist($sts_id,$question_id,$typeOfQuestion);
        //$pieces = explode(",", $ansId);
        if($state == 1){
            $ansVal = array(
                    "ac_sts"=>$sts_id,
                    "ac_question"=>$question_id,
                    "ac_value"=>$input
            );
            $DB->insert_record('ans_cbx', $ansVal, $returnid=false, $bulk=false);
        }else{
            $DB->delete_records("ans_cbx", array("ac_sts"=>$sts_id, "ac_question"=>$question_id, "ac_value"=>$input));
        }
        
     }
        
        
     //Is answer of question exist (combination of sts and question)
     /**
     * survey_management::isAnswerExist()
     * 
     * @param mixed $sts_id
     * @param mixed $question_id
     * @param mixed $typeOfQuestion
     * @return mixed ID or multiple ID
     */
     public function isAnswerExist($sts_id, $question_id, $typeOfQuestion){
        global $DB;
        $output = "";
        //Plain Text
        if($typeOfQuestion == 1){
            $sql = "select id from mdl_ans_plain where ap_sts = $sts_id and ap_question = $question_id";
            $ansID = $DB->get_record_sql($sql,array($sts_id,$question_id));
            $output .= $ansID->id;
            return $output;
        }else if($typeOfQuestion == 2){
            $sql = "select id from mdl_ans_ddl where ad_sts = $sts_id and ad_question = $question_id";
            $ansID = $DB->get_record_sql($sql,array($sts_id,$question_id));
            $output .= $ansID->id;
            return $output;
        }else if($typeOfQuestion == 3){
            $sql = "select id from mdl_ans_cbx where ac_sts = $sts_id and ac_question = $question_id";
            $ansID = $DB->get_records_sql($sql,array($sts_id,$question_id));
            foreach($ansID as $anId){
                $output .= $ansID->id.",";    
            }
            $output = trim($output,(strlen($output)-2));
            return $output;
        }else if($typeOfQuestion == 4){
            $sql = "select id from mdl_ans_scale where as_sts = $sts_id and as_question = $question_id";
            $ansID = $DB->get_record_sql($sql,array($sts_id,$question_id));
            $output .= $ansID->id;
            return $output;
        }
     }
}
//Statistic Management
class statistic_management{
    //Send email notification to multiple instructors
     /**
     * survey_management::isAnswerExist()
     * 
     * @param mixed $from
     * @param mixed $to
     * @param mixed $subject
     * @return mixed $content
     */
    public function send_email_notification($from, $fromName, $to, $subject, $content){
        $mail             = new PHPMailer();
        $body             = $content;//file_get_contents('contents.html');
        $mail->IsSMTP(); // telling the class to use SMTP
        $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                                   // 1 = errors and messages
                                                   // 2 = messages only
        $mail->SMTPAuth   = true;                  // enable SMTP authentication
        $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
        $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
        $mail->Port       = 465;                   // set the SMTP port for the GMAIL server
        $mail->Username   = "itec.moodle@gmail.com";  // GMAIL username
        $mail->Password   = "Moodle@123";            // GMAIL password
        
        $mail->SetFrom($from, $fromName);
        $mail->AddReplyTo($from, $fromName);
        $mail->Subject    = $subject;
        $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
        $mail->MsgHTML($body);
        
        $email_array = split(';',$to);
        $n = count($email_array);
        $address = "";
        for($i=0;$i<$n;$i++)
        {
            $address = $email_array[$i];
            $mail->AddAddress($address, "");
            //echo $address;
        }        
        //$mail->AddAttachment("images/phpmailer.gif");      // attachment
        //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
        
        if(!$mail->Send()) {
    		//$error = 'Mail error: '.$mail->ErrorInfo; 
    		return false;
    	} else {
    		//$error = 'Message sent!';
    		return true;
    	}
    }
}
//Benchmark Management
class benchmark_management{
    /**
     * benchmark_management::countITU()
     * 
     * @param mixed $valueITU 1/2/3
     * @param mixed $survey SurveyID
     * @param mixed $subject SubjectID
     */
    public function countITU($valueITU, $survey, $subject){
        global $DB;
        $sql = 
        "select count(*) as qty from mdl_slo_value where slov_sts in (select id from mdl_itus_teachers_subjects where sts_survey_id = ? and sts_subject_id = ?) and slov_value = ?";
        $record = $DB->get_record_sql($sql, array($survey, $subject, $valueITU));
        return $record->qty;
    }
    
    public function filterColLOs($sql){
        global $DB;
        //echo "\n".$sql."\n";
        return $DB->get_records_sql($sql);        
    }
    
    public function filterRowSubjects($sql){
        global $DB;
        //echo "\n".$sql."\n";
        return $DB->get_records_sql($sql);
    }
    
    public function deleteFilter($idFilter){
        global $DB;
        $DB->delete_records("filter", array("id"=>$idFilter));
    }
    
    public function reloadFilterOfSurvey($survey_id){
        global $DB;
        //$sql = "select * from mdl_filter where f_survey = ?";
        $filters = $DB->get_records('filter',array('f_survey'=>$survey_id));
        //$filters =  $DB->get_records_sql($sql); 
        
        return $filters;
    }
    
    public function saveFilterBenchmark(
                                        $coliop,
                                        $colqtyi,
                                        $colconnection1,
                                        $coltop,
                                        $colqtyt,
                                        $colconnection2,
                                        $coluop,
                                        $colqtyu,
                                        $rowiop,
                                        $rowqtyi,
                                        $rowconnection1,
                                        $rowtop,
                                        $rowqtyt,
                                        $rowconnection2,
                                        $rowuop,
                                        $rowqtyu, 
                                        $f_description, 
                                        $f_survey,
                                        $f_color_col,
                                        $f_color_row)
        {
        global $DB;
        //echo "insert:".$coliop."-".
//                                        $colqtyi."-".
//                                        $colconnection1."-".
//                                        $coltop."-".
//                                        $colqtyt."-".
//                                        $colconnection2."-".
//                                        $coluop."-".
//                                        $colqtyu."-".
//                                        $rowiop."-".
//                                        $rowqtyi."-".
//                                        $rowconnection1."-".
//                                        $rowtop."-".
//                                        $rowqtyt."-".
//                                        $rowconnection2."-".
//                                        $rowuop."-".
//                                        $rowqtyu."-".
//                                        $f_description."-". 
//                                        $f_survey;
        $filterdetail = array(
                    "coliop"=>$coliop,
                    "colqtyi"=>$colqtyi,
                    "colconnection1"=>$colconnection1,
                    "coltop"=>$coltop,
                    "colqtyt"=>$colqtyt,
                    "colconnection2"=>$colconnection2,
                    "coluop"=>$coluop,
                    "colqtyu"=>$colqtyu,
                    "rowiop"=>$rowiop,
                    "rowqtyi"=>$rowqtyi,
                    "rowconnection1"=>$rowconnection1,
                    "rowtop"=>$rowtop,
                    "rowqtyt"=>$rowqtyt,
                    "rowconnection2"=>$rowconnection2,
                    "rowuop"=>$rowuop,
                    "rowqtyu"=>$rowqtyu,
                    "f_survey"=>$f_survey,
                    "f_description"=>$f_description,                    
                    "f_color_col"=>$f_color_col,
                    "f_color_row"=>$f_color_row
        );
        return $DB->insert_record('filter', $filterdetail, $returnid=true, $bulk=false);        
    }
    
    public function getDepthOfSurvey($survey_id){
        global $DB;
        $sql = "select itus_depth_lo from mdl_itu_survey where id = ?";
        $record = $DB->get_record_sql($sql, array("id"=>$survey_id));
        return $record->itus_depth_lo;
    }
    
    //Count the number of assess ITU of combination subject-lo-survey
    /**
     * benchmark_management::countITUValueOf()
     * 
     * @param mixed $survey_id
     * @param mixed $subject_id
     * @param mixed $lo_id
     * @param mixed $itu (1/2/3)
     * @return qty
     */
    public function countITUValueOf($survey_id, $subject_id, $lo_id, $itu){
        global $DB;
        //$itu = 1/2/3 <=> I/T/U
        //echo "select count(id) as qty from mdl_slo_value from mdl_slo_value where slov_sts in (select id from mdl_itus_teachers_subjects where sts_survey_id = $survey_id and sts_subject_id = $subject_id) and slov_lo = $lo_id and slov_value = $itu";
        $output = $DB->get_record_sql("select count(id) as qty from mdl_slo_value where slov_sts in (select id from mdl_itus_teachers_subjects where sts_survey_id = ? and sts_subject_id = ?) and slov_lo = ? and slov_value = ?",array($survey_id,$subject_id,$lo_id,$itu));
        return $output->qty;
    }
    
    /**
     * benchmark_management::getOwnerOfITUValue()
     * 
     * @param mixed $survey_id
     * @param mixed $subject_id
     * @param mixed $lo_id
     * @param mixed value (I,T,U) (1,2,3))
     * @return list of instructor
     */
    public function getOwnerOfITUValue($survey_id, $subject_id, $lo_id, $ITUvalue){
        global $DB;
        $sql = "select u.id as user_id, u.username as instructor, sv.id, slov_sts  ";
        $sql .= "from mdl_slo_value sv, mdl_itus_teachers_subjects its, mdl_user u ";
        $sql .= "where slov_sts in (select id from mdl_itus_teachers_subjects where sts_survey_id = ? and sts_subject_id = ?) ";
        $sql .= "and slov_lo = ? and slov_value = ? and slov_sts = its.id and sts_teacher_id = u.id";    
        $output = $DB->get_records_sql($sql, array($survey_id, $subject_id, $lo_id, $ITUvalue));
        //echo "select u.id as user_id, u.username, sv.id, slov_sts from mdl_slo_value sv, mdl_itus_teachers_subjects its, mdl_user u where slov_sts in (select id from mdl_itus_teachers_subjects where sts_survey_id = $survey_id and sts_subject_id = $subject_id) and slov_lo = $lo_id and slov_value = $ITUvalue and slov_sts = its.id and sts_teacher_id = u.id<br/>";
        return $output;
    } 
    
    //check if los has child or not
    /**
     * benchmark_management::hasLoChild()
     * 
     * @param mixed $code
     * @return
     */
    public function hasLoChild($code){
        global $DB;
        //echo "select count(id) as childs from mdl_surveyed_los where sl_parent_lo = '$code'";
        $childs = $DB->get_records_sql("select count(id) as childs from mdl_surveyed_los where sl_parent_lo = '$code'",array());
        $number = 0;
        foreach($childs as $record){
            $number = $record->childs;
        }
        return $number;
    }

    /**
     * benchmark_management::getLoOfLevelOfSurvey()
     * 
     * @param mixed $survey
     * @param mixed $level
     * @param mixed $parent
     * @return
     */
    public function getLoOfLevelOfSurvey($survey, $level, $parent){
        global $DB;
        $los = array();
        if(!is_null($parent)){
            //echo $sql1."<br/>";
            $los = $DB->get_records_sql("select * from mdl_surveyed_los where sl_level = \"$level\" and sl_parent_lo = \"$parent\" and sl_survey = $survey",array());    
        }else{
            //echo $sql2."<br/>";
            $los = $DB->get_records_sql("select * from mdl_surveyed_los where sl_level = \"$level\" and sl_survey = $survey",array());
        }
        return $los;
    }
}

/*DEFINE CLASS AND FUNCTION END*/

?>
